package com.henry.chatkit.weight.photoview

import android.net.Uri
import android.view.View
import android.widget.ImageView
import android.widget.ProgressBar
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
//import com.davemorrissey.labs.subscaleview.ImageSource
//import com.davemorrissey.labs.subscaleview.SubsamplingScaleImageView
import com.github.iielse.imageviewer.core.ImageLoader
import com.github.iielse.imageviewer.core.Photo
import com.github.iielse.imageviewer.widgets.video.ExoVideoView2
//import com.google.android.exoplayer2.analytics.AnalyticsListener
import com.henry.chatkit.R
import com.henry.chatkit.utils.appContext
import com.henry.chatkit.utils.bindLifecycle
import com.henry.chatkit.utils.toast
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.io.File
import java.util.*

class ChatImageLoader : ImageLoader {

    override fun load(view: ImageView, data: Photo, viewHolder: RecyclerView.ViewHolder) {
        val it = (data as? PhotoData?)?.url ?: return
        Glide.with(view).load(it)
            .placeholder(view.drawable)
            .into(view)
    }

//    override fun load(exoVideoView: ExoVideoView2, data: Photo, viewHolder: RecyclerView.ViewHolder) {
//        super.load(exoVideoView, data, viewHolder)
//
//    }

//    override fun load(subsamplingView: SubsamplingScaleImageView, data: Photo, viewHolder: RecyclerView.ViewHolder) {
//        super.load(subsamplingView, data, viewHolder)
//        val it = (data as? PhotoData?)?.url ?: return
//        subsamplingDownloadRequest(it)
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.mainThread())
//                .doOnSubscribe { findLoadingView(viewHolder)?.visibility = View.VISIBLE }
//                .doFinally { findLoadingView(viewHolder)?.visibility = View.GONE }
//                .doOnNext { subsamplingView.setImage(ImageSource.uri(Uri.fromFile(it))) }
//                .doOnError { toast(it.toString()) }
//                .subscribe().bindLifecycle(subsamplingView)
//    }

    private fun subsamplingDownloadRequest(url: String): Observable<File> {
        return Observable.create {
            try {
                it.onNext(Glide.with(appContext()).downloadOnly().load(url).submit().get())
                it.onComplete()
            } catch (e: java.lang.Exception) {
                if (!it.isDisposed) it.onError(e)
            }
        }
    }

    private fun findLoadingView(viewHolder: RecyclerView.ViewHolder): View? {
        return viewHolder.itemView.findViewById<ProgressBar>(R.id.loadingView)
    }

}